package com.koozi;

/*
 Copyright 2012 Sven-Ove Bjerkan

 This file is part of KO-Ozi.

 KO-Ozi is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 KO-Ozi is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with KO-Ozi. If not, see <http://www.gnu.org/licenses/>.
 */


import com.koozi.versioncompare.VersionComparator;
import com.oziexplorer.OziAPI;
import com.oziexplorer.OziException;
import java.io.*;
import java.util.Properties;
import javax.swing.JOptionPane;
import org.discotools.io.IConnection;
import org.discotools.io.aprs.is.AprsIsProtocol;
import org.discotools.io.socket.SocketConnection;

/**
 * Provides application settings persistence.
 */
public class Settings {   
    private static Settings settings;
    private String projectPath;
    private String isAdminTrackers;
    private IConnection con;
    private AprsIsProtocol aprsIs;

    /**
     * Read in the settings, if they exist.
     */
    private Settings() {
        // Create protocol
        aprsIs = new AprsIsProtocol();

        // Create connection
        con = new SocketConnection("APRS-IS");

        try {
            // TEMP! Renamer gammel properties-fil
            File f = new File(System.getProperty("user.home"), "Oziauto.prop");
            if (f.isFile()) {
                f.renameTo(new File(System.getProperty("user.home"), "KO-Ozi.prop"));
            }
            // TEMP! Renamer gammel properties-fil

            props.load(new BufferedInputStream(
                    new FileInputStream(fileName)));
        } catch (IOException e) {
        }
    }

    /**
     * Singleton-class, so this gets the instance
     *
     * @return a settings-instance
     */
    public static synchronized Settings getInstance() {
        if (settings == null) {
            settings = new Settings();
        }
        return settings;
    }

    /**
     * Save the settings.
     *
     * @return true if the save was sucessful.
     */
    public boolean save() {
        // Open the properties file.
        try {
            props.store(new BufferedOutputStream(
                    new FileOutputStream(fileName)), "KO-Ozi settings");
        } catch (IOException e) {
            return false;
        }
        return true;
    }

    /**
     * Get the basepath.
     *
     * @return the basepath.
     */
    public String getPath() { 
        String path = "";
        try {
            path = props.getProperty("path", OziAPI.getExePath() + "\\data");
        } catch (OziException ex) {
            JOptionPane.showMessageDialog(null, "OziExplorer kjører ikke!",
                    "Feilmelding", JOptionPane.ERROR_MESSAGE);
            System.exit(1);
        }
        
        if (!isOziVersionOK()) {
            JOptionPane.showMessageDialog(null, "Du har for gammel versjon av OziExplorer!\n"
                    + "Du må minimum ha versjon 3.95.5m for å kjøre KO-Ozi.",
                    "Feilmelding", JOptionPane.ERROR_MESSAGE);
            System.exit(1);
        }
        
        return path;
    }

    // returns a string array that is a list of all
    // filenames that match the desired filename pattern
    public String[] getListOfFiles(String aDirectory, String ext) {
        // our filename filter (filename pattern matcher)
        class OnlyExtentionFilter implements FilenameFilter {

            private String ext;

            public OnlyExtentionFilter(String ext) {
                this.ext = ext;
            }

            public boolean accept(File dir, String s) {
                String foundExt = s.substring(s.length() - ext.length());
                if (foundExt.equals(ext)) {
                    return true;
                }
                return false;
            }
        }
        return new java.io.File(aDirectory).list(new OnlyExtentionFilter(ext));
    }

    public String getIsAdminTrackers() {
        return isAdminTrackers;
    }

    public void setIsAdminTrackers(String isAdmin) {
        isAdminTrackers = isAdmin;
    }

    /**
     * Set the basepath.
     *
     * @param path the basepath.
     */
    public void setPath(String path) {
        props.setProperty("path", path);
    }

    /**
     * How many tracks to save?
     *
     * @return number of tracks to save
     */
    public int getSaveTracks() {
        return Integer.parseInt(props.getProperty("numTracksSave", "50"));
    }

    public void setSaveTracks(String numTracksSave) {
        props.setProperty("numTracksSave", numTracksSave);
    }

    public void setBackupInterval(String interval) {
        props.setProperty("backupInterval", interval);
    }

    public int getBackupInterval() {
        return Integer.parseInt(props.getProperty("backupInterval", "10"));
    }
    
    public void setOpenSaveInterval(String interval) {
        props.setProperty("openSaveInterval", interval);
    }

    public double getOpenSaveInterval() {
        return Double.parseDouble(props.getProperty("openSaveInterval", "2"));
    }
    
    // Default projectname is "yyyy.mm.dd - "
    public String getDefaultProjName() {
        return TimeAndDate.getNiceDate(".") + " - ";
    }

    public void setProjectPath(String path) {
        projectPath = path;
    }

    public String getProjectPath() {
        return projectPath;
    }
    /**
     * Application settings filename.
     */
    private static final File fileName =
            new File(System.getProperty("user.home"), "KO-Ozi.prop");
    /**
     * Application settings container.
     */
    private final Properties props = new Properties();

    public Object clone() throws CloneNotSupportedException {
        throw new CloneNotSupportedException();
    }

    /**
     * @return the APRSIShost
     */
    public String getAPRSIShost() {
        return props.getProperty("APRSIShost", "");
    }

    /**
     * @param APRSIShost the APRSIShost to set
     */
    public void setAPRSIShost(String APRSIShost) {
        props.setProperty("APRSIShost", APRSIShost);
    }

    /**
     * @return the APRSISport
     */
    public String getAPRSISport() {
        return props.getProperty("APRSISport", "");
    }

    /**
     * @param APRSISport the APRSISport to set
     */
    public void setAPRSISport(String APRSISport) {
        props.setProperty("APRSISport", APRSISport);
    }

    /**
     * @return the APRSISuser
     */
    public String getAPRSISuser() {
        return props.getProperty("APRSISuser", "");
    }

    /**
     * @param APRSISuser the APRSISuser to set
     */
    public void setAPRSISuser(String APRSISuser) {
        props.setProperty("APRSISuser", APRSISuser);
    }

    /**
     * @return the APRSISpasscode
     */
    public String getAPRSISpasscode() {
        return props.getProperty("APRSISpasscode", "");
    }

    /**
     * @param APRSISpasscode the APRSISpasscode to set
     */
    public void setAPRSISpasscode(String APRSISpasscode) {
        props.setProperty("APRSISpasscode", APRSISpasscode);
    }

    /**
     * @return the APRSISfilter
     */
    public String getAPRSISfilter() {
        return props.getProperty("APRSISfilter", "");
    }

    /**
     * @param APRSISfilter the APRSISfilter to set
     */
    public void setAPRSISfilter(String APRSISfilter) {
        props.setProperty("APRSISfilter", APRSISfilter);
    }

    /**
     * @return the con
     */
    public IConnection getCon() {
        return con;
    }

    /**
     * @return the aprsIs
     */
    public AprsIsProtocol getAprsIs() {
        return aprsIs;
    }
    
    private boolean isOziVersionOK() {
        int result = -1;
        try {
            String version = OziAPI.getOziVersion();
            VersionComparator cmp = new VersionComparator();
            result = cmp.compare(version, "3.95.5m");
        } catch (OziException ex) {
          
        }
        return (result >= 0);
    }
}